<template>
  <el-dialog
    v-el-drag-dialog
    title="二次支付"
    append-to-body
    :visible.sync="visible"
    width="600px"
    @closed="reset"
  >
    <div class="content">
      <div ref="qrCodeUrl" class="qrcode-wrap" />
    </div>
  </el-dialog>
</template>

  <script>
  import { querySecondPayQrCode, querySecondPayOrderStatus } from '@/api'
  import QRCode from 'qrcodejs2'

  export default {
    name: 'SecondPay',
    data() {
      return {
        visible: false,
        temp: {},
        checkInterval: ''
      }
    },
    mounted() {
      console.log('parent', this.$parent)
    },
    methods: {
      open(temp) {
        return new Promise(resolve => {
          console.log('parent', this.$parent)
          this.resolve = resolve
          this.visible = true
          if (temp) {
            this.temp = temp
            this.getSecondPayQrCode({
              orderCode: temp.orderCode,
              corpCode: temp.corpCode,
              billType: 12
            })
          }
        })
      },
      async getSecondPayQrCode(params) {
        const res = await querySecondPayQrCode(params)
        const { codeUrl } = res.data
        this.creatQrCode(codeUrl)
        // 轮询开启
        this.timeEndOut = 1000
        this.checkingPay()
      },
      async creatQrCode(url) {
        // url = 'https://ibsbjstar.ccb.com.cn/CCBIS/QR?QRCODE=CCB9980003713130028832607'
        setTimeout(() => {
          this.$refs.qrCodeUrl.innerHTML = ''
          new QRCode(this.$refs.qrCodeUrl, {
            text: url,
            width: 300,
            height: 300,
            colorDark: '#000000',
            colorLight: '#ffffff',
            correctLevel: QRCode.CorrectLevel.Q
          })
        }, 500)
      },
      // 定时器
      checkingPay() {
        this.checkInterval = setInterval(() => {
          this.checkPayStatus()
        }, 1000)
      },
      async checkPayStatus() {
        if (this.payStatus === 2) {
          return
        }
        const res = await querySecondPayOrderStatus({ orderCode: this.temp.orderCode })
        if (res && res.data) {
          this.payStatus = res.data
          if (this.payStatus === 2) {
            this.$emit('paySuccess')
            this.$alert('二次支付成功', '', {
              confirmButtonText: '确定',
              showClose: false,
              callback: action => {
                this.visible = false
                this.$emit('confirmPaySuccess')
              }
            })
          }
        }
      },
      reset() {
        this.temp = {}
        this.$refs.qrCodeUrl.innerHTML = ''
        if (this.checkInterval) {
          clearInterval(this.checkInterval)
        }
      }
    }
  }
  </script>

  <style lang="scss" scoped>
    .qrcode-wrap {
      display: flex;
      justify-content: center;
      height: 300px;
    }
  </style>
